<template>
  <body id="paper">
  <el-form ref="loginForm" :model="loginForm" :rules="rules" class="login-container" label-position="left"
           v-loading="loading"
           element-loading-text="正在登录..." element-loading-spinner="el-icon-loading"
           element-loading-background="rgba(0, 0, 0, 0.8)" label-width="0px">
    <h3 class="login_title">系统登录</h3>
    <el-form-item prop="username">
      <el-input type="text" v-model="loginForm.username"
                auto-complete="off" placeholder="账号"></el-input>
    </el-form-item>
    <el-form-item prop="password">
      <el-input type="password" v-model="loginForm.password"
                auto-complete="off" placeholder="密码"></el-input>
    </el-form-item>
    <el-row>
      <el-col :span="15">
        <el-form-item prop="verifyCode">
          <el-input type="text" v-model="loginForm.verifyCode"
                    auto-complete="off" placeholder="验证码" @keydown.enter.native="login"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="8" :offset="1">
        <div id="div_captcha"><img :src="codeUrl" title="看不清，请点我" class="codeImg" @click="updateVerifyCode()"></div>
      </el-col>
    </el-row>
    <el-checkbox class="login_remember" v-model="loginForm.rememberME"
                 label-position="left"><span style="color: #505458">记住密码</span></el-checkbox>
    <el-form-item style="width: 100%">
      <el-button type="primary" style="width: 40%;background: #505458;border: none" @click="login">登录
      </el-button>
      <router-link to="register">
        <el-button type="primary" style="width: 40%;margin-left:10px;background: #505458;border: none">注册</el-button>
      </router-link>
    </el-form-item>
  </el-form>
  </body>
</template>

<script>
export default {
  name: "Login",
  data() {
    return {
      loading: false,
      codeUrl: '/static/testImg/captcha.jpeg', // 此处去后端获取
      rules: {
        username: [{required: true, message: '用户名不能为空', trigger: 'blur'}],
        password: [{required: true, message: '密码不能为空', trigger: 'blur'}],
        verifyCode: [{required: true, message: '验证码不能为空', trigger: 'blur'}]
      },
      loginForm: {
        username: '',
        password: '',
        verifyCode: '',
        rememberME: false
      },
      show: false,
    }
  },
  methods: {
    updateVerifyCode() {
      this.$axios.get('/api/getVerifyCode', {
        responseType: 'arraybuffer'
      }).then((response) => {
        const bufferUrl = 'data:image/jpeg;base64,' + btoa(new Uint8Array(response.data).reduce((data, byte) => data + String.fromCharCode(byte), ''))
        return bufferUrl
      }).then(data => {
        this.codeUrl = data
      }).catch(error => {
        console.log('验证码图片请求失败:' + error)
      });
    },
    login() {
      let _this = this;
      this.$refs.loginForm.validate(async (valid) => {
        if (valid) {
          this.loading = true;
          await this.$axios.post('/api/login', {
            username: this.loginForm.username,
            password: this.loginForm.password,
            verifyCode: this.loginForm.verifyCode,
            rememberMe: this.loginForm.rememberME
          }).then(response => {
            _this.loading = false;
            // 登录成功后将sessionId 作为登录成功的标识
            let userDetails = JSON.stringify(response.data.data.data.user)
            _this.$store.commit('setUserDetails', userDetails) // 将userDetails存入vuex 中
            let path = this.$route.query.redirect;
            this.$router.replace((path == '/' || path == undefined) ? '/home' : path);
          }).catch(function (error) {
            _this.loading = false;
            console.log('服务器异常' + error)
          })
        } else {
          return false;
        }
      })
    },
    showForm: function () {
      this.show = true
    },
    getPublicKey: function () {
      let _this = this;
      //页面加载时从后台获取RSA公钥
      this.$axios.get('/api/getPublicKey').then((response) => {
        let publicKey = response.data.data.publicKey;
        _this.$store.commit('setPublicKey', publicKey);
      })
    }
  },
  mounted() {
    this.updateVerifyCode() // 页面加载时获取验证码
    this.showForm()
    this.getPublicKey()
  }
}
</script>

<style scoped>
#paper {
  background: url("../../assets/img/background/login.jpeg") no-repeat center;
  height: 100%;
  width: 100%;
  background-size: cover;
  position: fixed;
}

body {
  margin: 0;
}

.login-container {
  border-radius: 15px;
  background-clip: padding-box;
  margin: 90px auto;
  width: 350px;
  padding: 35px 35px 15px 35px;
  background: #fff;
  border: 1px solid #eaeaea;
  box-shadow: 0 0 25px #cac6c6;
}

.login_title {
  margin: 0px auto 40px auto;
  text-align: center;
  color: #505458;
}

.login_remember {
  margin: 0px 0px 35px 0px;
  text-align: left;
}

.codeImg {
  text-align: center;
}
</style>
